/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.contacts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.async.DownloadNetworkImageTask;
import com.phonebooksharing.android.async.DownloadNetworkVideoTask;
import com.phonebooksharing.android.async.LoadAndroidPhotoTask;
import com.phonebooksharing.android.async.SendVoiceMessageTask;
import com.phonebooksharing.android.util.ContactUtils;
import com.phonebooksharing.android.util.GalleryUtilities;
import com.phonebooksharing.android.util.GeneralUtils;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.LocationUtil;
import com.phonebooksharing.android.widgets.adapters.GenericExpandableListAdapter;
import com.phonebooksharing.android.widgets.drawable.FastBitmapDrawable;
import com.phonebooksharing.android.widgets.header.ListWithHeaderHelper;
import com.phonebooksharing.android.widgets.pagination.ProgessbarListener;
import com.phonebooksharing.android.widgets.scroll.HorizontalScroller;
import com.phonebooksharing.dto.friend.ContactItem;
import com.phonebooksharing.dto.gallery.ImageGalleryItem;
import com.phonebooksharing.dto.gallery.VideoGalleryItem;
import com.phonebooksharing.dto.gallery.WishlistItem;

public class ContactBrowserActivity extends Activity implements View.OnLongClickListener, ProgessbarListener {
    
    private HorizontalScroller hs;
    private ProgressBar progress;
    private ContactItem focusFriend;
    
    public static final int ACTION_CALL             = 0,
                            ACTION_SMS              = 1,
                            ACTION_EMAIL            = 2,
                            ACTION_IM               = 3,
                            ACTION_SEND_TEXT        = 4,
                            ACTION_SEND_VOICE       = 5,
                            ACTION_IMAGE_GALLERY    = 6,
                            ACTION_VIDEO_GALLERY    = 7,
                            ACTION_WISHLIST_GALLERY = 8
                            ;
    
    public static final String FRIEND_ITEM  = "f";
    private int contactScreen, imageScreen, videoScreen, wishlistScreen; 
    
    private GenericExpandableListAdapter adapter;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_browser);
        
        hs = (HorizontalScroller) findViewById(R.id.scroller);
        hs.setOnLongClickListener(this);
        
        final Intent i = getIntent();
        focusFriend = (ContactItem)i.getSerializableExtra(FRIEND_ITEM);
        ContactItem fi = focusFriend;
        
        ((TextView)findViewById(android.R.id.text1)).setText(fi.name);
        ((TextView)findViewById(R.id.text3)).setText(fi.status);
        ((TextView)findViewById(R.id.text4)).setText(fi.location);
        
        ImageView icon = (ImageView)findViewById(android.R.id.icon);

        ContactUtils.setContactBorder(fi, findViewById(android.R.id.background));
        
        final FastBitmapDrawable ic = GalleryUtilities.getFromContactCache(fi.andID);
        if(ic != null) {
            icon.setImageBitmap(ic.getBitmap());
        } else {
            icon.setImageBitmap(GalleryUtilities.noPictureBitmap.getBitmap());
            long andID;
            if((andID = fi.andID) > 0) {
                new LoadAndroidPhotoTask(null, this, false).execute(andID, icon);
            } else {
//                new LoadNetworkImageTask(this).execute(cache.getIconID(), 60, 60, position, true /*isThumbnail*/, R.id.icon);
            }
        }
        final LayoutInflater li = LayoutInflater.from(this);

        final ExpandableListView lv = new ExpandableListView(this);
        lv.setCacheColorHint(0);
        HashMap<String, List<Map<String, ?>>> map = new LinkedHashMap<String, List<Map<String,?>>>();

        addStandard(map, fi.hasPbsAccount);
        final View v = li.inflate(R.layout.contact_browser_inner_layout, null);
        ((ViewGroup)v.findViewById(android.R.id.list)).addView(lv);
        ((TextView)v.findViewById(android.R.id.text1)).setText("Available Actions");
        hs.addView(v);

        if(fi.hasPbsAccount) {//don't need to browse otherwise
            int screen = 0;
            addMessaging(map);
            if(fi.contactCount > 0) {
                addContactBrowser(li);
                contactScreen = ++screen;
            }
            if(fi.isMyContact) {
                if(fi.imageCount > 0) {
                    addImageGallery(li);
                    imageScreen = ++screen;
                }
                if(fi.videoCount > 0) {
                    addVideoGallery(li);
                    videoScreen = ++screen;
                }
                if(fi.wishListCount > 0) {
                    addWishlistGallery(li);
                    wishlistScreen = ++screen;
                }
                if( fi.imageCount > 0 || fi.videoCount > 0 || fi.wishListCount > 0) addSharing(map);
            }
            addMaps(map);
        }
        
        adapter = new GenericExpandableListAdapter(this, map);
        lv.setAdapter(adapter);
        lv.expandGroup(0);
        lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                final Object group = adapter.getGroup(groupPosition);
                
                if(getString(R.string.action_standard).equals(group)) {
                    goActionStandard(childPosition);
                } else if(getString(R.string.action_messaging).equals(group)) {
                    goActionMessaging(childPosition);
                } else if(getString(R.string.action_sharing).equals(group)) {
                    goActionSharing(childPosition);
                } else if(getString(R.string.action_map).equals(group)) {
                    Location l = LocationUtil.getCurrentLocation(ContactBrowserActivity.this);
                    GeneralUtils.getDirections(ContactBrowserActivity.this, l.getLatitude(), l.getLongitude(), focusFriend.latitude, focusFriend.longitude);
                } 
                return false;
            }
        });
        
        hs.setDefaultScreen(0);
    }
    
    private void goActionSharing(int position) {
        switch (position) {
        case 0:
            hs.initListView(imageScreen);
            hs.snapToScreen(imageScreen);
            break;
        case 1:
            hs.initListView(videoScreen);
            hs.snapToScreen(videoScreen);
            break;
        case 2:
            hs.initListView(wishlistScreen);
            hs.snapToScreen(wishlistScreen);
            break;
        default:
            break;
        }
    }
    
    private void goActionStandard(int position) {
        switch (position) {
        case 0:
            GeneralUtils.dialPhone(this, focusFriend.primaryPhone);
            break;
        case 1:
            GeneralUtils.sendSMS(this, focusFriend.primaryPhone, "");
            break;
        case 2:
            GeneralUtils.sendEmail(this, focusFriend.primaryEmail, "", "");
            break;
        case 3:
            GeneralUtils.startIM(this, focusFriend.primaryEmail);
            break;
        default:
            break;
        }
    }
    
    private void goActionMessaging(int position) {
        switch (position) {
        case 0:
            GeneralUtils.postTextMessageDialog(this, "Text: ", focusFriend);
            break;
        case 1:
            Intent i = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
            startActivityForResult(i, ACTIVITY_RECORD_SOUND);
            break;
        default:
            break;
        }
    }

    public static final int ACTIVITY_RECORD_SOUND = 0;
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if(RESULT_OK == resultCode) {
            if(ACTIVITY_RECORD_SOUND == requestCode) {
                new SendVoiceMessageTask(this, -1, null, data.getDataString()).execute("New Audio");
            }
        }
    }
    
    protected void addStandard(HashMap<String, List<Map<String, ?>>> a, boolean hasPbsAccount) {
        ArrayList<Map<String, ?>> l = new ArrayList<Map<String, ?>>();
        
        l.add(ListWithHeaderHelper.createEntry(getString(R.string.action_standard_call),
                                               null, 
                                               getString(R.string.action_standard_call_txt),
                                               getString(R.string.action_standard_call_data, focusFriend.primaryPhone), 
                                               R.drawable.dash_shout,
                                               ACTION_CALL)); //TODO: calculate numbers
        
        l.add(ListWithHeaderHelper.createEntry(getString(R.string.action_standard_sms),
                                               null, 
                                               getString(R.string.action_standard_sms_txt),
                                               getString(R.string.action_standard_sms_data, focusFriend.primaryPhone), 
                                               R.drawable.send_sms,  
                                               ACTION_SMS));
        
        l.add(ListWithHeaderHelper.createEntry(getString(R.string.action_standard_email),
                                               null, 
                                               getString(R.string.action_standard_email_txt),
                                               getString(R.string.action_standard_email_data, focusFriend.primaryEmail), 
                                               R.drawable.email,  
                                               ACTION_EMAIL));

        l.add(ListWithHeaderHelper.createEntry(getString(R.string.action_standard_im),
                                               null, 
                                               getString(R.string.action_standard_im_txt),
                                               getString(R.string.action_standard_im_data, focusFriend.primaryEmail), 
                                               R.drawable.chat,  
                                               ACTION_IM));

//        if(!hasPbsAccount) {
//            l.add(ListWithHeaderHelper.createEntry("Invite to PBS", "Invite this person to join Phonebook Sharing", R.drawable.dash_videos));
//        }
        
        a.put(getString(R.string.action_standard), l);
    }
    
    protected void addMessaging(HashMap<String, List<Map<String, ?>>> a) {
        
        ArrayList<Map<String, ?>> l = new ArrayList<Map<String, ?>>();
//        l.add(ListWithHeaderHelper.createEntry("View Messages Wall", "View Messages Wall", R.drawable.dash_shout));
        l.add(ListWithHeaderHelper.createEntry(getString(R.string.action_messaging_text),
                                               null, 
                                               getString(R.string.action_messaging_text_txt),  
                                               "", 
                                               R.drawable.dash_messages,
                                               ACTION_SEND_TEXT));
        
        l.add(ListWithHeaderHelper.createEntry(getString(R.string.action_messaging_voice),
                                               null, 
                                               getString(R.string.action_messaging_voice_txt), 
                                               "",
                                               R.drawable.dash_videos,
                                               ACTION_SEND_VOICE));

        a.put(getString(R.string.action_messaging), l);
    }
    
    protected void addSharing(HashMap<String, List<Map<String, ?>>> a) {

        ArrayList<Map<String, ?>> l = new ArrayList<Map<String, ?>>();
        l.add(ListWithHeaderHelper.createEntry(getString(R.string.image_gallery),   
                                               "(" + focusFriend.imageCount + ")", 
                                               getString(R.string.action_sharing_image_txt), 
                                               "", 
                                               R.drawable.dash_photos, 
                                               ACTION_IMAGE_GALLERY));
        
        l.add(ListWithHeaderHelper.createEntry(getString(R.string.video_gallery),   
                                               "(" + focusFriend.videoCount + ")", 
                                               getString(R.string.action_sharing_video_txt), 
                                               "", 
                                               R.drawable.dash_videos, 
                                               ACTION_VIDEO_GALLERY));

        l.add(ListWithHeaderHelper.createEntry(getString(R.string.wishlist_gallery),   
                                               "(" + focusFriend.wishListCount + ")", 
                                               getString(R.string.action_sharing_wishlist_txt), 
                                               "", 
                                               R.drawable.gift, 
                                               ACTION_WISHLIST_GALLERY));

        a.put(getString(R.string.action_sharing), l);
    }
    
    protected void addMaps(HashMap<String, List<Map<String, ?>>> a) {

        ArrayList<Map<String, ?>> l = new ArrayList<Map<String, ?>>();
//        l.add(ListWithHeaderHelper.createEntry("View on Map", "View this person on the map", R.drawable.maps));
        l.add(ListWithHeaderHelper.createEntry(getString(R.string.action_map_direction), 
                                               getString(R.string.action_map_direction_txt), 
                                               R.drawable.maps));
        
        a.put(getString(R.string.action_map), l);
    }

    protected void addContactBrowser(LayoutInflater li) {
        final View v = li.inflate(R.layout.contact_browser_inner_layout, null);
        
        ContactBrowserListView cblv = new ContactBrowserListView(this, focusFriend.contactCount, (TextView)v.findViewById(android.R.id.text2), focusFriend);
        
        cblv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View arg1, int loc, long arg3) {
                ContactItem ci = (ContactItem)av.getAdapter().getItem(loc);
                Intent i = new Intent(ContactBrowserActivity.this, ContactBrowserActivity.class);
                i.putExtra(ContactBrowserActivity.FRIEND_ITEM, ci);
                startActivity(i);
            }
        });
        
        ((ViewGroup)v.findViewById(android.R.id.list)).addView(cblv);
        
        ((TextView)v.findViewById(android.R.id.text1)).setText(R.string.contact_browser);
        progress = (ProgressBar)v.findViewById(android.R.id.progress);
        hs.addView(v);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, R.string.contact_wall).setIcon(android.R.drawable.ic_menu_view);
        menu.add(1, 1, 1, R.string.contact_browser).setIcon(R.drawable.ic_menu_allfriends);
        menu.add(2, 2, 2, R.string.image_gallery).setIcon(android.R.drawable.ic_menu_gallery);
        menu.add(3, 3, 3, R.string.video_gallery).setIcon(android.R.drawable.ic_menu_camera);
        menu.add(4, 4, 4, R.string.wishlist_gallery).setIcon(android.R.drawable.ic_menu_manage);
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem item;
        item = menu.findItem(2);
        item.setEnabled(imageScreen > 0);

        item = menu.findItem(3);
        item.setEnabled(videoScreen > 0);

        item = menu.findItem(4);
        item.setEnabled(wishlistScreen > 0);

        return super.onPrepareOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0: {//contact wall
                hs.initListView(0);
                hs.snapToScreen(0);
                return true;
            }
            case 1: {//contact browser
                hs.initListView(contactScreen);
                hs.snapToScreen(contactScreen);
                return true;
            }
            case 2: {//imageScreen
                hs.initListView(imageScreen);
                hs.snapToScreen(imageScreen);
                return true;
            }
            case 3: {//videoScreen
                hs.initListView(videoScreen);
                hs.snapToScreen(videoScreen);
                return true;
            }
            case 4: {//wishlistScreen
                hs.initListView(wishlistScreen);
                hs.snapToScreen(wishlistScreen);
                return true;
            }
        }
        
        return false;
    }
    
    protected void addImageGallery(LayoutInflater li) {
        final View v = li.inflate(R.layout.contact_browser_inner_layout, null);
        
        ContactImageGalleryListView clv = new ContactImageGalleryListView(this, focusFriend.imageCount, (TextView)v.findViewById(android.R.id.text2), focusFriend);
        
        ((ViewGroup)v.findViewById(android.R.id.list)).addView(clv);
        ((TextView)v.findViewById(android.R.id.text1)).setText(R.string.image_gallery);
        progress = (ProgressBar)v.findViewById(android.R.id.progress);
        
        clv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View v, int loc, long id) {
                final ImageGalleryItem f = (ImageGalleryItem) av.getAdapter().getItem(loc);
                final int photoW = f.width;
                final int photoH = f.height;
                final long photoID = f.photoID;

//                final Display d1 = getWindowManager().getDefaultDisplay();
//                final int screenW = d1.getWidth();
//                final int screenH = d1.getHeight();
                //TODO: shouldnt be hard coded, but it changes the values when portrait mode
                final int screenW = 480;
                final int screenH = 320;

                final String[] s = new String[] {
                                        getString(R.string.image_gallery_size_orig, photoW, photoH), 
                                        getString(R.string.image_gallery_size_screen, screenW, screenH),
                                      };

                new AlertDialog.Builder(ContactBrowserActivity.this)
                                .setTitle(R.string.image_gallery_question_down)
                                .setItems(s, 
                  new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        int w, h;
                        if (which == 0) {// original
                            w = photoW;
                            h = photoH;
                        } else {// screen
                            w = screenW;
                            h = screenH;
                        }
                        new DownloadNetworkImageTask(ContactBrowserActivity.this).execute(photoID, w, h, f);
                    }
                }).create().show();
            }
        });
        
        hs.addView(v);
    }
    
    protected void addVideoGallery(LayoutInflater li) {
        final View v = li.inflate(R.layout.contact_browser_inner_layout, null);
        ContactVideoGalleryListView clv = new ContactVideoGalleryListView(this, focusFriend.videoCount, (TextView)v.findViewById(android.R.id.text2), focusFriend);
        
        ((ViewGroup)v.findViewById(android.R.id.list)).addView(clv);
        ((TextView)v.findViewById(android.R.id.text1)).setText(R.string.video_gallery);
        progress = (ProgressBar)v.findViewById(android.R.id.progress);
        
        clv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View v, int loc, long id) {
                final VideoGalleryItem f = (VideoGalleryItem) av.getAdapter().getItem(loc);
                Global.setTempBitmap(new FastBitmapDrawable(((BitmapDrawable)((ImageView)v.findViewById(R.id.icon)).getDrawable()).getBitmap()));
                
                new DownloadNetworkVideoTask(ContactBrowserActivity.this).execute(f.videoID, f);
            }
        });
        
        hs.addView(v);
    }
    
    protected void addWishlistGallery(LayoutInflater li) {
        final View v = li.inflate(R.layout.contact_browser_inner_layout, null);
        ContactWishlistGalleryListView clv = new ContactWishlistGalleryListView(this, focusFriend.wishListCount, (TextView)v.findViewById(android.R.id.text2), focusFriend);
        
        ((ViewGroup)v.findViewById(android.R.id.list)).addView(clv);
        ((TextView)v.findViewById(android.R.id.text1)).setText(R.string.wishlist_gallery);
        progress = (ProgressBar)v.findViewById(android.R.id.progress);
        
        clv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View v, int loc, long id) {
                final WishlistItem f = (WishlistItem) av.getAdapter().getItem(loc);
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(f.prodUrl));
                startActivity(i);
            }
        });
        
        hs.addView(v);
    }

    @Override
    public boolean onLongClick(View v) {
        // User long pressed on an item
        return true;
    }
    
    @Override
    public void setProgressStatus(int i) {
        progress.setVisibility(i);
    }
}
